package com.example.springbootrediscache.service;

import com.example.springbootrediscache.entity.User;
import org.springframework.cache.annotation.*;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


/**
 * 使用@CacheConfig注释，我们可以在类级别将一些缓存配置简化到单个位置，这样就不必多次声明：
 */
@CacheConfig(cacheNames = "user")
@Service
public class UserServiceImpl {
    static Map<Long, User> userMap = new HashMap<>();

    {
        User user1 = new User(1L, "a", "xxx");
        userMap.put(1L, user1);
    }

    @Cacheable(cacheNames = {"findUserById"}, key = "#id")
    public User findUserById(Long id) {
        System.out.println("直接查询");
        return userMap.get(id);
    }

    @CachePut(cacheNames = {"findUserById"}, key = "#user.id")
    public User insertUser(User user) {
        userMap.put(user.getId(), user);
        return user;
    }

    @CachePut(cacheNames = {"findUserById"}, key = "#user.id")
    public User updateUserById(User user) {
        userMap.put(user.getId(), user);
        return user;
    }

    @CacheEvict(cacheNames = {"findUserById"}, key = "#id", beforeInvocation = true, allEntries = true)
    public void deleteUserById(Long id) {
        userMap.remove(id);
    }

    @Caching(evict = {
            @CacheEvict("addresses"),
            @CacheEvict(value = "directory", key = "#user.id")})
    public String getAddress(User user) {
        return "";
    }


}
